[JavaWorld Main Page] [Nuts & Bolts] [News & Views] [Java Resources]

Beginner's JavaScript

Java without all the tedious programming? Not quite.

Summary
JavaScript provides the means to perform useful, simple tasks to improve the style of your Web site. This is the first in a series of columns on JavaScript. For now we'll assume we're all beginners and progress toward programmer level.

By Rawn Shah

If you`ve seen all the interesting things that the world of Java is bringing to the Web, but are afraid of trying to learn a programming language this complex, you should consider JavaScript, a joint effort from Sun and Netscape. Among the variety of amazing features that Netscape Communications Corp. includes in version 2.0 of its browser is the client-side scripting feature initially introduced as LiveScript. Renamed JavaScript, this language is an off-shoot of the Netscape-Sun Java project; the members of the Sun Java-team described this scripting system, before it was available to the public, as a rapid means of writing small useful scripts and applets. Netscape's directional focus they underwent last December introduced a whole new set of development partners interested in building applets and applications for the new version.

In this inaugural issue of JavaWorld, we will introduce JavaScript to interested novices with a short series of articles covering technical aspects of JavaScript and its functionality. Since I would rather we not try to fly before we can walk, I will first go over the very basics of the language and its structure. We will do very simple examples that you can add to your page and then try some more interesting projects in future articles.

Another Java?
Contrary to some beliefs, JavaScript is not merely a decaffeinated version of Java for beginners and novices. The LiveScript/JavaScript animal is quite separate from direct Java applets and applications since it provides the functionality for a different niche in the market. It is, primarily, a solution for Client-side APIs in Netscape Navigator 2.0.

The discussion of the use of Client-side Application Programming Interfaces (APIs) in the world of the Web, once Server-side APIs had caught a hold, is still ongoing. The push toward moving the application processing from an already weighted server to the local user's interface came with the improvements in end-user desktop technology, both in hardware and software. With the increase from 486-based to Pentium-based and 68000-based to PowerPC-based PCs, the ever dropping price of secondary storage and memory, the technical demands of the average user are also increasing.

JavaScript provides this Client-side API to take care of the nuisances of static Web text. Netscape is also working on creating a server-side system with JavaScript, possibly with a link to the Common Gateway Interface (CGI) for backward compatibility. It is currently available on all the Netscape 2.0 beta version browsers and runs on all the different platforms. Note to Mac users: just because JavaScript is available in the Mac browser, it does not mean that your Mac Netscape 2.0 browser can do Java applets. The Macintosh and Windows 3.1 versions of the Netscape 2.0 still do not support Java.

Java-lite
Formerly known as Java-lite or Mocha internally, JavaScript takes away some of the tedium involved in writing heavy-duty Java applets to do simple calculations or browser control functions. The most obvious difference between the two is that JavaScripts are immediately interpreted by the browser from the source code, whereas Java applets need to be precompiled into a class before actual use. For the lay person this means that the scripts may run slower; each line is interpreted separately, usually one keyword and parameter combination at a time, rather than having faster compiled and code that can be immediately executed by the Java runtime environment within the browser.

Although you have to give up some object-oriented features available in Java, you still have objects with their methods and variables providing the necessary utility. You can define objects but not classes of objects. The difference between an object and a class, in layspeak, is the difference between a building and its architectural plan; once you have a building, you can use it until its end; but if you have the building's architectural plan, you can build other buildings just like it or make major modifications to it.

You also have to give up object inheritance. In our building analogy, with classes and inheritance you can effectively make modifications to the architectural plan to make a better building, or one more suitable for its use. Classes and inheritance exist to facilitate and improve the functionality and reuse of objects. In short scripts, you probably will not reuse an object too often so it is not really necessary. JavaScript provides loose type declaration for the lazy.

Programmers in the classic C, Pascal, and even Java worlds are familiar with strong type declarations where you have to specify that a variable is a string, an integer, etc. In JavaScript, similar to how it works in the Perl language, you simply use a variable as necessary and it is up to the programmer to remember not to suddenly change a string into an integer or boolean. This lenient factor is partially due to the fact that the designers do not expect users to write too intensively detailed a program. For run of the mill scripting, it is easier to live without strong type declarations.

True Java applets do not generally interact with the HTML of a Web page. Each applet is limited to a subarea of the page. Although an applet can be made to communicate with several other applets on the same page, it cannot, however, change the text of the same HTML page in which it is located. Javascript, on the other hand, was created solely to allow HTML writers to allow different HTML tags and elements to interact with each other. An input box in one HTML form can modify the HTML information inside another HTML page.

In truth, there are actually ways of controlling your browser from within Java applets. However, to do simple things like calculations within forms, changing other frames within the browser, etc., takes a substantial amount of coding for a simple task. Javascript was made to allow HTML writers to implement such functionality without spending hours upon hours writing Java code.

Another important difference, although not directly stated, is that you do not have the large set of class libraries that you can use with Java. This limits the scripts to simple calculations and event processing. For example, you cannot start a separate network connection within JavaScript and download a new class over the network into your hierarchy to build upon your basic browser's ability dynamically over the network; this is something you can do with Java, on the other hand.

So what can you do with it?
Now that you know the what and why, we will continue in the next issue with the when and the how. As we mentioned, JavaScripts can quickly deliver interactive Web forms with a greater degree of efficiency. Previously, using server-based scripts, the programmer had to develop a series of Forms and scripts, or multiple steps within the same script, to perform error-checking and correction. With JavaScript, error-checking can be quickly taken care of with the built-in event-handling mechanisms based upon user interaction with the Web form. With JavaScript you can also develop dynamic Forms that change on the user's screen depending upon the HTML checkboxes, radio buttons or other input fields that you fill in.

JavaScript also can be used for small applets that handle quick functions or calculations that would otherwise require the painstaking aid of server-based scripts. For users who do not have direct access or control of the server to configure and develop server-based scripts, this alternative scripting mechanism saves the day. Netscape 2.0 HTML tags used for Forms, including the FORM, INPUT, and TEXTAREA, have been "enhanced" to allow event-driven activities such as mouse clicks, focus, entered text, etc., to call scripts within the document. Netscape also has created a new tag known as SCRIPT. All information between the open and close SCRIPT tags is interpreted as JavaScript. This tag pair can be placed anywhere in the BODY section of the HTML file, or in the HEAD section. If the script tag-pair is placed in the HEAD section, the code within that script is executed before the body of the HTML page is completely downloaded. This allows interpretation of any code to be done before the user enters any text into the form itself. so events can be handled properly.

You may in turn want to add scripts within the body of the text if for example, you wish to create a dynamic form displaying different form tags or HTML code depending upon what you enter into the earlier form elements.

The script need not be located within the same HTML file. It can be located elsewhere and downloaded separately from the HTML file, the same way images are kept separately. Unfortunately, at the time of this writing (using 2.0 Beta 6), this could not be tested because it has yet to be implemented by Netscape.

The First JavaScript example shows an example of the of the SCRIPT tag with direct code immediately following it.

<HTML>
<HEAD>
<TITLE>My First JavaScript Page</TITLE>
<SCRIPT LANGUAGE="Javascript">

<!--
document.write("This text will appear before the actual body of the HTML 
page. 
<P>");
// -->

</SCRIPT>
</HEAD>
<BODY>
<H3> This is my first JavaScript Web page! </H3>
</BODY>
</HTML>

First JavaScript example

Click here to see the output of the First JavaScript example

If you look at the HTML code, you will notice some things that may seem peculiar at first. For example, the HTML comment tag "<!--" encloses the body of the script itself. This is done so that other non-Netscape browsers don't confuse the JavaScript code as text and actually display it on the screen as part of the text of the page. If you are using an older beta version of Netscape 2.0, before the beta 5 release, the code will not work unless you change the tag from LANGUAGE="Javascript" to LANGUAGE="Livescript". LiveScript was the precursor name to JavaScript; the older betas do not understand the new name, of course. You should use LANGUAGE="Javascript" from now on.

In this example we do something simple: Write a line of HTML text into the page. No one would actually do just that unless they were necessarily trying to be difficult. We offer this example first because we have yet to get to the constructs and syntax of the language itself. If we wanted to keep the actual code elsewhere, we would change the SCRIPT tag to as shown below

<SCRIPT LANGUAGE="Javascript" 
SRC="http://www.mydomain.com/myscript.js">
</SCRIPT>

This feature will not be available until future versions (probably version 2.1, unfortunately), so just keep it in mind. With this method of locating code elsewhere, the HTML file is much cleaner and you do not need to add the HTML comment tag to hide the script from other browsers; they simply won't understand the SCRIPT tag and will ignore it completely. Here's another small note about these tags: we named the file with the extension .js as opposed to .java. Although it is not really necessary to give an extension, it is good practice, and using .js instead of .java (the required extension for true Java code) will reduce confusion. Note that you cannot use a compiled Java applet as a JavaScript; despite some similarity in name and structure, Java and JavaScript are two distinct languages.

Now let's move on with the actual syntax of JavaScript.

Syntax
If you have seen C, C++ or even Java code before, you may be familiar with the syntax already. The language has a set of reserved words that act as the control mechanisms of the language. In addition, there is a set of built-in functions that perform tasks like writing a line of text, doing mathematical calculations and the like. You can create variables that store data that can be modified or reused. Only a handful of raw data types are used.

Although you can essentially have one monolithic set of instructions, several hundred lines long, to do an entire program, most programmers break their code into smaller useful sections. These smaller pieces of code can help you perform groups of instructions at a time by invoking just one function. It saves you time from rewriting the same instructions over and over within the program. JavaScript provides these sets of code as functions that can be executed as a single unit. Within the block of the function is a set of JavaScript that performs everything needed by that function. None of the code within a function is executed until the function is actually called elsewhere in the code.

Reserved characters and operators
A good number of the non-alphabetic characters in the ASCII set are used as operators within the language. These operators perform specific simple mathematical, and logical functions. An operator usually has two other components: the lvalue (the value to the left of it) and the rvalue (the value to the right). C and C++ programmers will be glad to know that the operator sets are almost identical to their own.

The basic set of mathematical operators are + (addition), - (subtraction or arithmetic negation), * (multiplication), / (division), % (modulo, or remainder after you divide) and = (assignment); as a side note, the lvalue for the assignment operator is always a variable. In addition to these operators, there are -- (decrement an integer variable) and ++ (increment a integer variable), bitwise operators such as || (OR two values), && (AND two values), ! (NEGATE a value), ^ (XOR two values), << (shift bits to the left), <<< (shift bits to the left and fill spaces with zeros), >> (shift bits to the right) and >>> (shift bits to the right and fill spaces with zeros.) With the exception of the increment, decrement, and arithmetic negation, each of these operators can be combined with the assignment operator like += (increment lvalue by the amount in the rvalue). The combination assignment operators are there as a shorthand when performing a mathematical operation on a variable and then assigning the result of that operation back to the variable:

variable = variable * 42;
// The above line is identical to the next line variable *= 42;

To allow more complex calculations, you can use the parentheses to section the parts of the calculation.

zzz = (xxx * 32) / (yyy + xxx);

For logical or numerical comparison, operators are as follows: < (less than), > (greater than), == (equal to), != (not equal to), <= (less than or equal to), >= (greater than or equal to). Please keep in mind the significant difference between == and =. It is one of the most common mistakes made by novices in the C language, and in JavaScript as well. BASIC programmers should also know that != and not <> is used as the not-equal-to function. The semicolons that you see at the end of each line are used to separate different "lines" of code. You can actually have a number of executable code segments on the same line of text. This has the same effect as keeping the two lines separate. It just saves space if needed. For example,

variable *= 42; zzz = (xxx * 32) / (yyy + xxx);

Aside from being used as a mathematical addition operator, the plus sign (+) is used as a concatenation operator if its lvalue or rvalue is a string. For example,

yourname = "Dave" 
line_of_text = "What are you doing " + yourname + "?"; 

The variable, line_of_text, now becomes "What are you doing Dave?"

The quotation marks are used to indicate strings. The single-quote character (') can also be used to delineate a string. You need a pair to indicate the start and end of the string. The difference between the two is that the standard double-quote mark (") allows special character combinations to indicate non-printable ASCII characters like the tab, newline, etc. To indicate these meta-characters you use the backslash (\) character. For example, the tab is indicated with a \t. The backslash is also used for escape operators that would otherwise be misunderstood. To print the backslash character itself, you simply use two of them (\\) in your string.

The brackets are used in a special data type known as the array. An array is a set of values of the same type that can be indexed directly. For example, to access the first element of an array, you would use myarrary[0]. Note that arrays start at 0, not 1. We will take a more in-depth look at arrays later. The braces ({ and }) are used to indicate a block of statements. These blocks are used inside language constructs like the common if...then...else construct and the while loop, and as delimiters for functions.

Comments are delimited with /* and */, or you can use // to indicate that any following characters to the end of a line comprise a comment. The last operator uses two characters -- the question mark (?) and the colon (:). The ? : operator is shorthand for the if...then...else language construct. The same statement could otherwise be written using the reserved words if and else. For example,

if (notMine == true)
{
   someoneElses = true;
}
else
{
   someoneElses = false;
}

can be easily rewritten in shorthand as:

someoneElses = (notMine == true) ? true : false;

Finally, as a note to C and C++ programmers, the * and -> operators do not exist. Perl programmers should know that the dollar sign ($) is not used to indicate variables and the pound sign (#) is not used to indicate the start of a comment in your code. Perl programmers will find (to their dismay) that there are no pattern-matching or substitution operators either.

Data types and variables
The four basic data types available in JavaScript are the object (a generic data type that can be anything), the number (floating point or decimal), the string (a set of text characters), and the boolean (true or false values). A variable is indicated by a word name and is case sensitive. Variable names also allow for the use of the underscore character (_), but nothing else other than ASCII alphanumeric characters. Also, variable names can begin only with an alphabetic character, not a number or underscore. The example below shows several variables being assigned values.

myvariable = "A line of text";
count = 0;
Super_Long_VariableNamethatishardtoread = "";
WorldIsRound = true;

The first variable is a string. The second variable stores a numerical value, and the third is another string (currently blank). The last is a boolean value that can be either true or false. With these basic types it is possible to do much of the work. In addition, there are two more advanced data types known as the array and the function pointer.

Statements
Statements are whole executable lines of JavaScript; they give structure to a script. Without these constructs, it is possible to do only simple operations and built-in functions. Each construct employs one or more reserved words. Here is a full table of these reserved words for currently implemented statements:

break           comment         continue 
for             for...in        function 
if...else       return          var 
while           with    

In truth, there is another entire series of reserved words that have not been implemented in the current release of JavaScript but are still recognized by the interpreter and cannot be used within your code:

abstract        boolean         byte            case 
catch           char            class           const 
default         do              double          extends 
false           final           finally         float 
goto            implements      import          instanceof 
int             interface       long            native 
null            package         private         protected
public          short           static          super 
switch          synchronized    throw           throws 
transient       try             void    

These words primarily are reserved words in Java that currently are not implemented in JavaScript.

if...else
The simplest to grasp is the if..then...else construct. Basically, if a condition is true, the script will perform a certain action; if it is not true then it will do something else. For example,

if (variable > 20)
{
   ...
   ...
}
else
{
...
}

The actions are kept within blocks of statements. You can combine these into a whole series of if...else constructs tagged on after the else. Unfortunately, there is no switch statement right now to provide a comparison of one value to a set of others and perform statements for each.

while
The while loop provides a means of repeating a series of commands while a certain condition is true. It is certainly possible to be stuck forever within a while loop if the condition never becomes false, so make sure you have a way out.

count = 0;
while (count < 10)
{
   write("Hello.\n");
   count++;
}

for
A more subtle way of performing the same action, as shown in the example for the while loop, is to use the for loop. It is another shorthand that makes things easier to read, but for all intents and purposes it is identical in function to the previous example.

for (count = 0; count < 10; count++)
{
  write("Hello.\n");
}

There are three sections within the parentheses; the initialization phase count = 0; the comparison phase count < 10; and the modification phase count++. The initialization phase is executed only once before the body of the loop begins. Next, the comparison phase checks the status of the loop. Then the body of the loop itself is executed. Once the body is done, the modification section is executed. As you can see, each of these phases or sections is separated by a semicolon.

for..in
The for..in construct executes a block of code for all elements in a set of data. For example,

for count in myArray
{
  write(myArray[count]);
}

This example script will print the contents of each and every element in the array.

function
The function keyword begins the definition of a subroutine that can be called in other parts of the program. A function is declared as:

function myfunction(parameter1, parameter2)
{
  // body of the function
}

The keyword is followed by a name for the function. The rules for function names are the same as for variable names. After the name within the parentheses is a list of all the parameters. In our example the function has only two parameters, but it actually can have as many parameters as you need. Unlike C and other languages, the loose typing of JavaScript does not require that you indicate what data type these parameters are. The data types are interpreted when the function is called elsewhere. For example, suppose we have defined a function to find the average of two numbers. This function can be called in the code else as shown below.

xxx = 23;
yyy = 14;
averaged_value = Average(xxx, yyy);

After any processing within itself, the function can return a value by using the return keyword followed by a value. The actual code for the Average function we used above might be:

function Average(value1, value2)
{
  average = (value1 + value2) / 2;
  return average;
 }

break, continue
The break and continue keywords are used in loops to effect a forced escape out of the loop, or to skip past the rest of the code within a block and continue the loop in its next iteration. For example,

count = 0;
while (count < 10)
{
  if (count == 5) 
    break;
  
  write(count + "...");
  count++;
}

This example script prints out the numbers 0 through 5, although the loop conditional says it should continue iterating until count becomes 10. The if..then with the break statement causes the loop to end at 5.

Let's look at another example.

for iteration in myArray
{
   if (Math.odd(iteration))
     continue;

   writeln(myArray[iteration]);
}
This example makes use of the Math function to check for odd numbers in the iteration and prints out only the values contained in the even slots of the array.

Using objects
A small set of objects are readily available for use within your code. In C and BASIC, these are usually known as library functions and can be used to perform trigonometric functions, print information to the screen, etc. The object is the basic unit of object-oriented programming systems (OOPS). Each object usually has certain features or variables and also a set of functions or methods associated with the object. Please note that we use the words function and method interchangeably; true OOPS programmers only refer to them as methods, but to bring some familiarity to readers who have done programming in non-object-oriented languages like C and BASIC, we will continue using this term interchangeably.

anchor          the HTML anchor tag object
applet          a Java applet object; currently this is not yet 
implemented
button          an HTML INPUT tag of type "button" 
checkbox        an HTML INPUT tag of type "checkbox"
Date            an object that contains a variety of methods to print, 
                calculate, and interchange dates
document        the object describing an HTML page 
form            the controlling object for an entire HTML FORM 
history         an object of the current browsers history list
link            an HTML link object
location        an object describing a URL
Math            an object that contains mathematical constants, 
trigonometric
                functions, and other basic non-arithmetic methods
password        an HTML INPUT tag of type "password"
radioButton     an HTML INPUT tag of type "radio"
reset           an HTML INPUT tag of type "reset"
selection       a text selection within the HTML TEXTAREA or INPUT type 
"text" tags
string          the string data type with a variety of methods for 
printing and
		manipulating strings
submit          the HTML INPUT tag of type "submit"
text            the HTML INPUT tag of type "text"
textArea        the HTML TEXTAREA tag (Note: the selection object is 
separate
		from the textArea object itself)
window          the object describing the current browser or document 
window

Descriptions of JavaScript objects
This list of JavaScript objects is exhaustive to what has been implemented in Netscape Navigator. You have already seen us use the write and writeln, two of the most commonly used methods that are automatically interpreted as part of the document object. You have also seen the use of the Math object. Of this list, most are basic tags you would find in an HTML FORM. Other useful but less-easily understood objects are the window and the document objects that control behavior of the document itself. You will notice that no objects for opening files or network connections exist yet. Currently this is a security risk, but there is hope for the future: Vendors are making noise about including such features to create a more powerful scripting language.

Event Handlers
Most of the functions of JavaScript are invoked within a FORM or document with the help of Event Handlers. Each FORM type has a set of events that it responds to such a selecting a checkbox or defocusing or "blurring the focus" of a text field. The complete list of event handlers and what event they respond to is shown below:

onBlur          when an text, selection, or textarea field looses focus
onChange        when a selection, text, textarea field is modified or 
looses 	
		focus
onClick         when a button, checkbox, link, or radio object is clicked 
or 
		selected
onFocus         when a selection, text, or textarea field is focused
onLoad          when a window or a FRAME is loaded
onMouseOver     when the mouse is moved over a hyperlink
onSelect        when text in a text or textarea field is selected
onSubmit        when a FORM is submitted
onUnload        when a window or FRAMESET is closed or a new page is 
displayed 

An event handler is added as a new parameter to a given tag. For example,

<INPUT TYPE="button" VALUE="Total Amount" 
ONCLICK="doTotalAmount(this)">

This example will attempt to perform a calculation as described by the text. It uses the new Button type input field, which is used only with client-side scripting.

<A HREF="second_page.html" ONMOUSEOVER="window.status='Go on to Page 2'; 
return true;">Next Page</A>

The second example shows a quick way for you to display a text message in the status bar of the browser about the link the user is about to select.

Simple calculation with JavaScript
In this example, we will take two values that have been entered into INPUT fields in a FORM and calculate a new value from them.

<HTML>
<HEAD>
<TITLE>Calculate this, buddy!</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
var myAge;
var dadsAge;

function HowOld(form)
{
  var difference;
  difference = dadsAge - myAge;
  form.Fdiff.value = difference;
}

function SetMyAge(age)
{
  myAge = age.value;
}

function SetDadsAge(age)
{
  dadsAge = age.value;
}

// -->
</SCRIPT>
<BODY>
<FORM METHOD="POST">
<TABLE CELLSPACING=15>
<TR>
<TD>Enter your Age:</TD>
<TD><INPUT TYPE=text NAME=Fmyage SIZE=4 
ONCHANGE="SetMyAge(this)"></TD>
</TR>
<TR>
<TD>Enter your Dads Age:</TD>
<TD> <INPUT TYPE=text NAME=Fdadsage SIZE=4 
ONCHANGE="SetDadsAge(this)"></TD>
</TR>
<TR>
<TD COLSPAN=2><INPUT TYPE=BUTTON ONCLICK="HowOld(this.form)" 
VALUE="How much older is Dad?"></TD>
</TR>
<TR>
<TD COLSPAN=2>You are <INPUT TYPE=text NAME="Fdiff" VALUE="" 
SIZE=3> 
years younger than your dad. <P></TD>
</TR>
</TABLE>
</FORM>
</BODY>
</HTML>

A short calculation Javascript
(Click Here to see Functional example of this script)

This HTML file only contains a table with three INPUT fields (one of them is really an output field) and one button to perform the calculation. Without getting too detailed in making a complex spreadsheet, this file shows the very basic of adding two numbers; something you learned back in kindergarten. It employs "safe" means of accessing variables within the document through accessor functions like SetMyAge() and SetDadsAge(). Essentially, you will be dealing with objects that are more complex than a simple integer. You could create an object with several properties, each of which needs to be set, and can do so with similar accessor functions. Note also that this file sets a value of an object within the document; in this case, the INPUT tag named "Fdiff" is set to the value of the calculation. Things we haven't added yet include error-checking methods to make sure that you actually did enter values for your age and your dad's age.

Conclusion
In the next issue of JavaWorld, we will take a look at larger and more useful programs that can be written in JavaScript. Primarily we will take care of error checking within HTML forms and then move on to creating Netscape FRAMEs which interact with JavaScript. Needless to say, reading about JavaScript will not simply do the trick; just like playing tennis or football, you have to actually do it to make the most of it. To get a good start, read the documentation for JavaScript found on Netscape's Web site. Also, if you are not part of the Netscape Developer Program, you may wish to join so you can participate in the secured newsgroups that discuss JavaScript avidly. []

About the author
Rawn Shah is vice president of RTD Systems & Networking Inc., a network consultancy and integrator based in Tucson, AZ. He can be reached at rawn.shah@javaworld.com.

What did you think of this article?
-Excellent! -Okay -Poor ----- -Too long -Just right -Too short
Comments:

[JavaWorld Main Page] [Nuts & Bolts] [News & Views] [Java Resources]


[(c) Copyright 1996 Web Publishing Inc., an IDG Communications company]

If you have problems with this magazine, contact webmaster@javaworld.com
URL: http://www.javaworld.com/javaworld/jw-03-1996/jw-03-javascript.intro.html
Last updated: 22 February 1996